<template>
    <div>
        <tableHeaderFrom :item-from="itemFromData" @getFormData="getFormDataVal" />
        <div class="addButton">
            <el-button v-limit="'添加'" type="primary" :icon="Plus" @click="dialogModel.dialogFormVisible = true">添加</el-button>
        </div>
        <tableLayout :table-data="statusTableData.tableData" :data="statusTableData.data" :loading="statusTableData.loading" @operationChange="eventTaleOptionClick"></tableLayout>

        <el-dialog v-model="dialogModel.dialogFormVisible" width="30%" :title="dialogModel.title" :close-on-click-modal="false" @close="dialogCancel" @open="opendialog" @closed="closedorgan">
            <el-form ref="formRef" :model="formInitData.form" :rules="formInitData.rules" label-width="80px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="formInitData.form.username" placeholder="输入用户名" />
                </el-form-item>
                <el-form-item label="编码" prop="inviteCode">
                    <el-input v-model="formInitData.form.inviteCode" placeholder="输入编码" />
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="formInitData.form.phone" placeholder="输入手机号" />
                </el-form-item>

                <el-form-item label="类型" prop="type">
                    <el-select v-model="formInitData.form.type" style="width: 100%" placeholder="请选择">
                        <el-option v-for="item in formInitData.typeOptions" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogCancel">取消</el-button>
                    <el-button type="primary" @click="submit">保存</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import tableHeaderFrom from '@/dynamicCustom/components/tableHeaderFrom.vue';
import tableLayout from '@/dynamicCustom/components/tableLayout.vue';
import { HeaderFromOption, DataType } from '@/interface';
import API from '@/api';
import { onMounted, reactive, shallowReactive, ref, nextTick } from 'vue';

import type { FormInstance } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';

const formRef = ref<FormInstance>();
const itemFromData: HeaderFromOption = [
    {
        type: 'input',
        label: '用户名',
        modeVal: 'username',
        width: '262px',
        placeholder: '请输入'
    },
    {
        type: 'select',
        label: '类型',
        modeVal: 'type',
        width: '262px',
        placeholder: '请选择',
        options: [
            {
                value: 'app',
                label: 'app'
            },
            {
                value: 'web',
                label: 'web'
            },
            {
                value: 'mobile',
                label: 'mobile'
            }
        ]
    }
];

/** 表格响应式数据初始化 */
const statusTableData = reactive({
    tableData: [],
    loading: true,
    data: [
        { prop: 'username', label: '用户名' },
        { prop: 'createTime', label: '创建日期' },
        { prop: 'inviteCode', label: '编码' },
        { prop: 'phone', label: '手机号' },
        { prop: 'type', label: '类型' },
        {
            slot: true,
            label: '操作',
            slotName: 'operation',
            width: '140%',
            operation: [
                {
                    label: '修改',
                    types: 'primary',
                    onClick: 'editClick'
                },
                {
                    label: '删除',
                    types: 'danger',
                    icon: 'Delete',
                    onClick: 'delClick'
                }
            ]
        }
    ] as DataType
});
/** 表单响应式数据初始化 */
const formInitData = reactive({
    // 表单内容
    form: {
        username: '', // 用户名
        inviteCode: '', // 编码
        phone: '', // 手机号
        type: '' // 类型
    } as { [key in string]: string | number },
    // 表单类型下拉框
    typeOptions: [
        { value: 'app', label: 'app' },
        { value: 'web', label: 'web' },
        { value: 'mobile', label: 'mobile' }
    ],
    // 表单校验
    rules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        inviteCode: [{ required: true, message: '请输入编码', trigger: 'blur' }],
        phone: [
            { required: true, message: '请输入手机号', trigger: 'blur' },
            {
                pattern: /^1[3456789]\d{9}$/,
                message: '请输入正确的手机号',
                trigger: 'blur'
            }
        ],
        type: [{ required: true, message: '请选择类型', trigger: 'change' }]
    }
});
/** 编辑弹框数据初始化 */
const dialogModel = shallowReactive({
    dialogFormVisible: false,
    title: '编辑内容'
});

/** 初始化表格 */
const tableInit = async (data: { username?: string; type?: string } = {}) => {
    statusTableData.loading = true;

    const resp = await API.member_list({ method: 'GET', data });
    statusTableData.tableData = resp;
    setTimeout(() => {
        statusTableData.loading = false;
    }, 200);
};

/** 表格操作按钮点击事件 */
const eventTaleOptionClick = (item: any) => {
    /** 编辑事件 * */
    const editEventChange = (row: any) => {
        formInitData.form.id = '';
        Object.keys(formInitData.form).forEach((items: any) => {
            formInitData.form[items] = row[items];
        });
        dialogModel.dialogFormVisible = true;
    };

    /** 删除事件 * */
    const delEventChange = ({ id }: any) => {
        window.$messageBox
            ?.confirm('确认删除', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
            .then(async () => {
                try {
                    const res = await API.admin_member({ urlVal: id, method: 'DELETE' });
                    window.$message?.success('删除成功');
                    tableInit();
                } catch (err) {}
            })
            .catch(() => {});
    };

    const map = new Map([
        ['editClick', editEventChange],
        ['delClick', delEventChange]
    ]);
    map.get(item.eventName)?.call(this, item.row);
};

/** 显示弹框回调 */
const opendialog = () => {
    if (!formRef.value) return;
    nextTick(() => {
        formRef.value?.clearValidate();
    });
};

/** 关闭弹框回调  */
const dialogCancel = () => {
    dialogModel.dialogFormVisible = false;
};

/** 关闭弹框动画结束后回调  */
const closedorgan = () => {
    Object.keys(formInitData.form).map((key: string) => {
        (formInitData.form as { [key in string]: any })[key] = '';
        return formInitData.form;
    });
    delete formInitData.form.id;
};

/** 保存编辑 */
const submit = () => {
    formRef.value?.validate(async valid => {
        if (valid) {
            const isEdit = formInitData.form?.id;
            const apiName = isEdit ? 'member_update' : 'member_add';
            const method = isEdit ? 'PUT' : 'POST';
            const data = isEdit ? { id: isEdit, ...formInitData.form } : { ...formInitData.form };

            try {
                const resp = await API[apiName]({ method, data });
                console.log(resp, 'resp');
                if (resp.code === 1) {
                    window.$message?.success('操作成功');
                }
            } catch {}
            dialogCancel();
            tableInit();
        }
    });
};

/**
 *  - 表格数据筛选
 *  - item - 筛选的数据
 */
const getFormDataVal = (item: any) => {
    console.log('筛选值：', item);

    tableInit(item);
};

onMounted(() => {
    tableInit();
});
</script>
<style lang="scss" scoped>
.addButton {
    margin: 15px;
}
</style>
